﻿namespace MSSqlSchemaDoc.Provider.MicrosoftSqlServer
{
    using System.Data;
    using System.Data.SqlClient;
    using System.Text;
    using MSSqlSchemaDoc.Core.DataStructures;
    using MSSqlSchemaDoc.Provider.MicrosoftSqlServer.Helpers;
    using MSSqlSchemaDoc.Provider.MicrosoftSqlServer.Resources;

    /// <summary>
    /// Contains the helper methods for synonym objects.
    /// </summary>
    public partial class SqlScriptingManager
    {
        /// <summary>
        /// Fetches a list of synonyms and extracts the information for each.
        /// </summary>
        /// <param name="connection">An open connection to the database.</param>
        /// <param name="objectType">The synonym object type.</param>
        private void ScriptSynonyms(SqlConnection connection, DataStructureObjectType objectType)
        {
            // Load data
            StringBuilder query = new StringBuilder(this.queryManager.Synonyms());
            SqlCommand c = new SqlCommand(query.ToString(), connection);

            using (IDataReader reader = c.ExecuteReader())
            {
                // Build the full text catalog objects
                while (reader.Read())
                {
                    string name = DataReaderHelper.GetString(reader, "ObjectName");

                    this.OnBeginScriptingObject(name);

                    Synonym s = new Synonym();

                    s.ObjectId = DataReaderHelper.GetInt(reader, "ObjectId").Value;
                    s.Name = name;
                    s.BaseObjectName = DataReaderHelper.GetString(reader, "BaseObjectName");

                    // Documentation
                    if (this.IncludeDocumentationObjects)
                    {
                        s.Documentation = this.ConstructDocumentationObject<SynonymDocumentation>(s.Name, s.Schema);
                    }

                    this.OnCompleteScriptingObject(s, name);
                }
            }
        }
    }
}
